package com.jingbian.cppccbackend.controller.admin;

import com.jingbian.cppccbackend.entity.Admins;
import com.jingbian.cppccbackend.entity.Department;
import com.jingbian.cppccbackend.entity.Result;
import com.jingbian.cppccbackend.service.admin.AdminsService;
import com.jingbian.cppccbackend.service.admin.SuperService;
import com.jingbian.cppccbackend.utils.ResultUtil;
import com.jingbian.cppccbackend.entity.vo.PageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PutMapping;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 超级管理员信息表 前端控制器
 * </p>
 *
 * @author yezi
 * @since 2025-02-09
 */
@Slf4j
@RestController
@Validated
@RequestMapping("/admins")
public class SuperController {
    @Autowired
    private SuperService superService;
    @Autowired
    private AdminsService adminsService;

    //查看提案部门列表
    @GetMapping("/getProList")
    public Result<List<Department>> getProList() {
        List<Department> proDepartments = superService.getProList();
        return ResultUtil.success(proDepartments);
    }

    //查看社情民意部门列表
    @GetMapping("/getPubList")
    public Result<List<Department>> getPubList() {
        List<Department> pubDepartments = superService.getPubList();
        return ResultUtil.success(pubDepartments);
    }

    // 新增提案部门
    @PostMapping("/addProDepartment")
    public Result<String> addProDepartment(@RequestBody Department department) {
        superService.addProDepartment(department);
        return ResultUtil.success("添加提案部门成功");
    }

    // 新增社情民意部门
    @PostMapping("/addPubDepartment")
    public Result<String> addPubDepartment(@RequestBody Department department) {
        superService.addPubDepartment(department);
        return ResultUtil.success("添加社情民意部门成功");
    }

    // 删除提案部门
    @DeleteMapping("/deleteProDepartment/{id}")
    public Result<String> deleteProDepartment(@PathVariable Integer id) {
        superService.deleteProDepartment(id);
        return ResultUtil.success("删除提案部门成功");
    }

    // 删除社情民意部门
    @DeleteMapping("/deletePubDepartment/{id}")
    public Result<String> deletePubDepartment(@PathVariable Integer id) {
        superService.deletePubDepartment(id);
        return ResultUtil.success("删除社情民意部门成功");
    }

    // 修改管理员密码
    @PutMapping("/updatePassword/{aid}")
    public Result<String> updatePassword(
            @PathVariable Integer aid,
            @RequestParam String newPassword) {

        superService.updatePassword(aid, newPassword);
        return ResultUtil.success("密码修改成功");
    }

    //获取管理数据
    @GetMapping("/getAdmins")
    public Result<PageVO<Admins>> getAdmins(
            Integer pageNum,
            Integer pageSize,
            @RequestParam(required = false,defaultValue = "asc") String sortType,
            @RequestParam(required = false) String permissionType,
            @RequestParam(required = false) String statusType,
            @RequestParam(required = false) String searchText
    ) {
        PageVO<Admins> admins = superService.getAdmins(
                pageNum, pageSize, sortType, permissionType, statusType, searchText);
        return ResultUtil.success(admins);
    }

    // 注销管理员
    @PutMapping("/disable/{aid}")
    public Result<String> disableAdmin(@PathVariable Integer aid) {
        superService.disableAdmin(aid);
        return ResultUtil.success("管理员注销成功");
    }

    // 根据管理员 ID 查询管理员信息
    @GetMapping("/getAdminById/{aid}")
    public Result<Admins> getAdminById(@PathVariable Integer aid) {
        Admins admin = superService.getAdminById(aid);
        return ResultUtil.success(admin);
    }

    // 更新管理员信息
    @PutMapping("/updateAdmin/{aid}")
    public Result<String> updateAdmin(
            @PathVariable Integer aid,
            @RequestBody Admins admin) {
        // 确保要更新的管理员ID与路径参数一致
        if (!Objects.equals(admin.getAid(), aid)) {
            return ResultUtil.fail("管理员ID不匹配");
        }
        superService.updateAdmin(admin);
        return ResultUtil.success("管理员信息更新成功");
    }

    // 新增普通管理员
    @PostMapping("/addAdmin")
    public Result<String> addAdmin(@RequestBody Admins admin) {
        superService.addAdmin(admin);
        return ResultUtil.success("添加普通管理员成功");
    }

    @GetMapping("/exportAdmins")
    public ResponseEntity<byte[]> exportAdmins(
            @RequestParam(required = false, defaultValue = "asc") String sortType,
            @RequestParam(required = false) String permissionType,
            @RequestParam(required = false) String statusType,
            @RequestParam(required = false) String searchText) throws IOException {

        log.info("开始导出管理员列表Excel");

        try {
            // 获取管理员列表数据
            List<Admins> adminsList = superService.getAdminsForExport(sortType, permissionType, statusType, searchText);
            log.info("获取到 {} 条数据", adminsList.size());

            // 创建工作簿
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("管理员列表");

                // 设置表头样式
                CellStyle headerStyle = workbook.createCellStyle();
                headerStyle.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
                headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
                Font headerFont = workbook.createFont();
                headerFont.setBold(true);
                headerStyle.setFont(headerFont);

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] header = {"账号", "控制人", "权限数量", "状态", "提案部门", "社情民意部门",
                        "用户管理", "会议管理", "活动管理", "签到管理", "新闻发布",
                        "主办编辑", "提案管理", "社情民意管理"};

                for (int i = 0; i < header.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(header[i]);
                    cell.setCellStyle(headerStyle);
                    sheet.autoSizeColumn(i);
                }

                // 填充数据
                int rowNum = 1;
                for (Admins admin : adminsList) {
                    Row row = sheet.createRow(rowNum++);
                    row.createCell(0).setCellValue(admin.getAccount());
                    row.createCell(1).setCellValue(admin.getController());
                    row.createCell(2).setCellValue(calculatePermissionCount(admin));
                    row.createCell(3).setCellValue(admin.getStatus());
                    row.createCell(4).setCellValue(admin.getPropositionsDepName() != null ? admin.getPropositionsDepName() : "");
                    row.createCell(5).setCellValue(admin.getPublicDepName() != null ? admin.getPublicDepName() : "");
                    row.createCell(6).setCellValue(admin.getManageUsers() ? "是" : "否");
                    row.createCell(7).setCellValue(admin.getManageMeetings() ? "是" : "否");
                    row.createCell(8).setCellValue(admin.getManageEvents() ? "是" : "否");
                    row.createCell(9).setCellValue(admin.getManageCheckIns() ? "是" : "否");
                    row.createCell(10).setCellValue(admin.getPublishNews() ? "是" : "否");
                    row.createCell(11).setCellValue(admin.getEditHomePage() ? "是" : "否");
                    row.createCell(12).setCellValue(admin.getManagePropositions() ? "是" : "否");
                    row.createCell(13).setCellValue(admin.getManagePublic() ? "是" : "否");
                }

                // 写入字节数组
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                workbook.write(outputStream);
                byte[] content = outputStream.toByteArray();

                // 设置响应头
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
                String filename = URLEncoder.encode("管理员列表.xlsx", StandardCharsets.UTF_8).replaceAll("\\+", "%20");
                headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename*=UTF-8''" + filename);

                log.info("Excel文件生成成功，大小: {} bytes", content.length);
                return new ResponseEntity<>(content, headers, HttpStatus.OK);
            }
        } catch (Exception e) {
            log.error("导出Excel失败", e);
            throw new RuntimeException("导出Excel失败: " + e.getMessage());
        }
    }

    // 计算权限数量
    private int calculatePermissionCount(Admins admin) {
        return (admin.getManageUsers() ? 1 : 0) +
               (admin.getManageMeetings() ? 1 : 0) +
               (admin.getManageEvents() ? 1 : 0) +
               (admin.getManageCheckIns() ? 1 : 0) +
               (admin.getPublishNews() ? 1 : 0) +
               (admin.getEditHomePage() ? 1 : 0) +
               (admin.getManagePropositions() ? 1 : 0) +
               (admin.getManagePublic() ? 1 : 0);
    }

    @GetMapping("/checkAccount/{account}")
    public Result<Boolean> checkAccountExists(@PathVariable String account) {
        boolean exists = superService.checkAccountExists(account);
        return ResultUtil.success(exists);
    }

}



